<?php
declare(strict_types=1);

namespace App\Services;

use App\Core\Config;
use PDO;
use PDOException;

final class Database
{
    private static ?PDO $pdo = null;

    public static function pdo(): PDO
    {
        if (self::$pdo instanceof PDO) {
            return self::$pdo;
        }

        $driver = Config::get('DB_DRIVER', 'mysql') ?? 'mysql';
        $host   = Config::get('DB_HOST', '127.0.0.1') ?? '127.0.0.1';
        $port   = Config::get('DB_PORT', '3306') ?? '3306';
        $db     = Config::get('DB_DATABASE', 'mycms') ?? 'mycms';
        $user   = Config::get('DB_USERNAME', 'root') ?? 'root';
        $pass   = Config::get('DB_PASSWORD', '') ?? '';
        $charset = Config::get('DB_CHARSET', 'utf8mb4') ?? 'utf8mb4';

        if ($driver !== 'mysql') {
            throw new PDOException('Only mysql driver is supported in this skeleton.');
        }

        $dsn = "mysql:host={$host};port={$port};dbname={$db};charset={$charset}";

        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];

        self::$pdo = new PDO($dsn, $user, $pass, $options);
        return self::$pdo;
    }
}